<template>
  <div class="history-container">
    <div class="header">
      <h1>请求历史</h1>
      <p>查看和管理您的 HTTP 请求历史记录</p>
    </div>

    <div class="history-actions">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchQuery"
            placeholder="搜索URL、方法或状态码..."
            clearable
            @input="filterHistory"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="methodFilter" placeholder="筛选方法" clearable @change="filterHistory">
            <el-option label="全部" value=""></el-option>
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
            <el-option label="PATCH" value="PATCH"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button 
            type="danger" 
            @click="clearAllHistory"
            :disabled="filteredHistory.length === 0"
          >
            清空历史
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="history-content">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="filteredHistory.length === 0" class="empty-state">
        <el-empty description="暂无历史记录" />
      </div>

      <div v-else class="history-list">
        <el-card
          v-for="item in filteredHistory"
          :key="item.id"
          class="history-item"
          shadow="hover"
        >
          <div class="history-item-header">
            <div class="request-info">
              <el-tag
                :type="getMethodType(item.method)"
                size="small"
                class="method-tag"
              >
                {{ item.method }}
              </el-tag>
              <span class="url" :title="item.url">{{ item.url }}</span>
            </div>
            <div class="status-info">
              <el-tag
                :type="getStatusType(item.status)"
                size="small"
                v-if="item.status"
              >
                {{ item.status }}
              </el-tag>
              <span class="timestamp">{{ formatTime(item.timestamp) }}</span>
            </div>
          </div>

          <div class="history-item-details">
            <div class="details-row">
              <span class="label">响应时间：</span>
              <span class="value">{{ item.responseTime || 'N/A' }}ms</span>
            </div>
            <div class="details-row" v-if="item.headers && Object.keys(item.headers).length > 0">
              <span class="label">请求头：</span>
              <span class="value">{{ Object.keys(item.headers).length }} 个</span>
            </div>
            <div class="details-row" v-if="item.body">
              <span class="label">请求体：</span>
              <span class="value">{{ getBodyPreview(item.body) }}</span>
            </div>
          </div>

          <div class="history-item-actions">
            <el-button
              type="primary"
              size="small"
              @click="resendRequest(item)"
            >
              重新发送
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewDetails(item)"
            >
              查看详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteHistoryItem(item.id)"
            >
              删除
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 详情弹窗组件 -->
    <HttpDetail
      :visible="detailsVisible"
      :request-item="selectedItem"
      @update:visible="detailsVisible = $event"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import HttpDetail from './HttpDetail.vue'

const router = useRouter()
const loading = ref(true)
const history = ref([])
const filteredHistory = ref([])
const searchQuery = ref('')
const methodFilter = ref('')
const detailsVisible = ref(false)
const selectedItem = ref(null)

// 加载历史记录
const loadHistory = async () => {
  loading.value = true
  try {
    const result = await new Promise((resolve) => {
      chrome.storage.local.get(['httpHistory'], (result) => {
        resolve(result.httpHistory || [])
      })
    })
    
    history.value = result.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
    filteredHistory.value = history.value
  } catch (error) {
    console.error('加载历史记录失败：', error)
  } finally {
    loading.value = false
  }
}

// 筛选历史记录
const filterHistory = () => {
  let filtered = history.value

  // 按搜索查询筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.url.toLowerCase().includes(query) ||
      item.method.toLowerCase().includes(query) ||
      (item.status && item.status.toString().includes(query))
    )
  }

  // 按方法筛选
  if (methodFilter.value) {
    filtered = filtered.filter(item => item.method === methodFilter.value)
  }

  filteredHistory.value = filtered
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 获取方法标签类型
const getMethodType = (method) => {
  const types = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return types[method] || 'info'
}

// 获取状态码标签类型
const getStatusType = (status) => {
  if (!status) return 'info'
  if (status >= 200 && status < 300) return 'success'
  if (status >= 300 && status < 400) return 'info'
  if (status >= 400 && status < 500) return 'warning'
  return 'danger'
}

// 获取请求体预览
const getBodyPreview = (body) => {
  if (!body) return ''
  const bodyStr = typeof body === 'string' ? body : JSON.stringify(body)
  return bodyStr.length > 50 ? bodyStr.substring(0, 50) + '...' : bodyStr
}

// 重新发送请求
const resendRequest = (item) => {
  // 通过路由传递数据到发送页面
  router.push({
    path: '/',
    query: {
      url: item.url,
      method: item.method,
      headers: JSON.stringify(item.headers || {}),
      body: typeof item.body === 'string' ? item.body : JSON.stringify(item.body || '')
    }
  })
}

// 查看详情
const viewDetails = (item) => {
  selectedItem.value = item
  detailsVisible.value = true
}

// 处理详情弹窗关闭
const handleDetailClose = () => {
  detailsVisible.value = false
  selectedItem.value = null
}

// 删除历史记录项
const deleteHistoryItem = async (id) => {
  try {
    await new Promise((resolve) => {
      chrome.storage.local.get(['httpHistory'], (result) => {
        const currentHistory = result.httpHistory || []
        const updatedHistory = currentHistory.filter(item => item.id !== id)
        chrome.storage.local.set({ httpHistory: updatedHistory }, () => {
          resolve()
        })
      })
    })
    
    // 更新本地数据
    history.value = history.value.filter(item => item.id !== id)
    filterHistory()
  } catch (error) {
    console.error('删除历史记录失败：', error)
  }
}

// 清空所有历史记录
const clearAllHistory = async () => {
  try {
    await new Promise((resolve) => {
      chrome.storage.local.set({ httpHistory: [] }, () => {
        resolve()
      })
    })
    
    history.value = []
    filteredHistory.value = []
  } catch (error) {
    console.error('清空历史记录失败：', error)
  }
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.history-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  font-size: 14px;
}

.history-actions {
  margin-bottom: 30px;
}

.history-content {
  min-height: 400px;
}

.loading {
  margin: 20px 0;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  transition: all 0.3s ease;
}

.history-item:hover {
  transform: translateY(-2px);
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.request-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.method-tag {
  min-width: 60px;
  text-align: center;
}

.url {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #409eff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 400px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.timestamp {
  color: #909399;
  font-size: 12px;
}

.history-item-details {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
  font-size: 13px;
}

.details-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
}

.history-item-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-container {
    padding: 10px;
  }
  
  .history-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .history-item-details {
    flex-direction: column;
    gap: 8px;
  }
  
  .history-item-actions {
    flex-wrap: wrap;
  }
  
  .url {
    max-width: 200px;
  }
}
</style>
